/**
 * 服务器入口文件
 * 初始化Express应用和Socket.io
 */
const express = require('express');
const http = require('http');
const cors = require('cors');
const dotenv = require('dotenv');
const path = require('path');
const connectDB = require('./config/db');
const { notFound, errorHandler } = require('./config/errorHandler');
const socketSetup = require('./socket');

// 加载环境变量
dotenv.config();
console.log('环境变量加载状态：PORT =', process.env.PORT);
console.log('MongoDB URI =', process.env.MONGO_URI ? '已设置' : '未设置');

// 连接数据库
connectDB();

// 创建Express应用
const app = express();

// 中间件
app.use(cors({
  origin: '*',  // 允许所有来源访问
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
  credentials: true,
  exposedHeaders: ['Content-Length', 'X-Requested-With', 'X-Total-Count']
}));

// 添加CORS预检请求处理
app.options('*', (req, res) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
  res.sendStatus(200);
});

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// 添加请求日志中间件
app.use((req, res, next) => {
  console.log(`${req.method} ${req.path} - ${new Date().toISOString()}`);
  next();
});

// 上传文件夹
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 根路径处理
app.get('/', (req, res) => {
  res.json({ message: '聊天应用API服务器已启动' });
});

// 路由
app.use('/api/auth', require('./routes/auth'));
app.use('/api/users', require('./routes/user'));
app.use('/api/messages', require('./routes/message'));
app.use('/api/conversations', require('./routes/conversation'));
app.use('/api/contacts', require('./routes/contact'));

// 错误处理中间件
app.use(notFound);
app.use(errorHandler);

// 创建HTTP服务器
const server = http.createServer(app);

// 设置Socket.io
socketSetup(server);

// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, '0.0.0.0', () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
}); 